//
//  WSCoinsPayController.m
//  CharonTVProject
//
//  Created by karong on 2023/8/10.
//

#import "WSCoinsPayController.h"
#import "WSRechargeCell.h"
#import "WSPurchaseRequest.h"
#import "AppDelegate.h"
#import "WSPurchaseManager.h"
#import "WSGoods.h"
#import "UIButton+ImageAlign.h"
#import "WSPayRequest.h"

@interface WSCoinsPayController () <WSPurchaseManagerDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mainViewBottom;
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (nonatomic, strong) NSArray * dataArray;
@property (weak, nonatomic) IBOutlet UILabel *coinsLabel;
@property (weak, nonatomic) IBOutlet UIButton *autoUnlockBtn;
@property (weak, nonatomic) IBOutlet UILabel *subTitleLabel;
@property (weak, nonatomic) IBOutlet UIButton *moreBtn;
@property (weak, nonatomic) IBOutlet UIButton *payBtn;
@property (nonatomic, assign) NSInteger selectIndex;
@end

@implementation WSCoinsPayController

@synthesize dataArray = _dataArray;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addObserver];
    [self layoutMainView];
    [self layourAutoUnlockBtn];
    [self loadGoodsListRequest];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.mainViewBottom.constant = 0;
        [self.view uploadLayout];
    });
}
- (void)addObserver {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(layoutMainView) name:WSCoinsChangeNotification object:nil];
}

- (void)layoutMainView {
    self.coinsLabel.text = WSSF(@"%@：%ld", APPLocalized(@"剧豆餘額"),(long)appUserCenter.coins);
    [self.moreBtn setButtonImageTitleStyle:(WSButtonImageTitleStyleRight) padding:4];
    NSInteger price = self.charonTV_video.coins - appUserCenter.coins;
    self.selectIndex = (price > 0)?0:-1;
    self.subTitleLabel.text = (price > 0)?WSSF(@"%@%ld剧豆%@", APPLocalized(@"還需"),price,APPLocalized(@"可解鎖本集")):WSSF(@"%ldcoins%@", self.charonTV_video.coins,APPLocalized(@"可解鎖本集"));
}

- (void)layourAutoUnlockBtn {
    [self.autoUnlockBtn setButtonImageTitleStyle:(WSButtonImageTitleStyleLeft) padding:7.5];
    self.autoUnlockBtn.selected = appConfig.isAutoPay;
}

- (void)loadGoodsListRequest {
    WeakSelf
    [WSToast loading];
    [WSPurchaseRequest loadcharonTV_GoodsListWithGoods_type:1 success:^(NSArray *array) {
        weakSelf.dataArray = array;
        [WSPurchaseManager shared].delegate = weakSelf;
        [WSPurchaseManager shared].products = array;
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)payGoods:(WSGoods *)goods {
    if (goods.SKProduct) {
        if (appUserCenter.isLogin) {
            [WSPurchaseManager shared].delegate = self;
            [[WSPurchaseManager shared] createOrderWithProduct:goods];
        }
        else {
            [((AppDelegate*)([UIApplication sharedApplication].delegate)) initMainPage];
        }
    }
}

- (void)payVideo {
    [WSPayRequest payWithChapter_id:self.charonTV_video.id success:^(NSString *string) {
        self.charonTV_video.url = string;
        if ([self.delegate respondsToSelector:@selector(coinsPayControllerReloadAction:)]) {
            [self.delegate coinsPayControllerReloadAction:self.charonTV_video];
        }
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}
    
- (IBAction)payAction:(id)sender {
    if (appUserCenter.coins >= self.charonTV_video.coins && self.selectIndex < 0) {
        [self payVideo];
    }
    else if (self.selectIndex < 0) {
        [WSToast simple:APPLocalized(@"剧豆不足，請充值")];
    }
    else {
        [self payGoods:self.dataArray[self.selectIndex]];
    }
}

- (IBAction)moreAction:(id)sender {
    if ([self.delegate respondsToSelector:@selector(coinsPayControllerMoreAction)]) {
        [self.delegate coinsPayControllerMoreAction];
    }
}

- (IBAction)autoAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    appConfig.isAutoPay = sender.selected;
}
#pragma mark - WSPurchaseManagerDelegate
- (void)didAppleReceiveResponse {
    [WSToast dismiss];
    [self.listView reloadData];
}

- (void)purchaseManager:(WSPurchaseManager *)manager updateStatus:(WSPurchaseStatus)status object:(id)object {
    switch (status) {
        case WSPurchaseStatusSuccess:
        {
            [self payVideo];
        }
            break;
        case WSPurchaseStatusCancel:
            [WSToast simple:APPLocalized(@"支付失敗")];
            break;
        default:
            break;
    }
}
#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return MAX(self.dataArray.count, 2);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WSRechargeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WSRechargeCell" forIndexPath:indexPath];
    [cell setDataWithObject:self.dataArray[indexPath.row] select:self.selectIndex == indexPath.row];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeZero;
    size.width = WSScreenWidth - 12 - 12;
    size.height = 51.5 + 12;
    return size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.selectIndex == indexPath.row) {
        self.selectIndex = -1;
    }
    else {
        self.selectIndex = indexPath.row;
    }
    [self.listView reloadData];
    
}
@end
